package com.analysis.utils;

import com.analysis.entity.References;
import com.analysis.enums.AddTypeEnum;
import com.analysis.enums.ModelChatClientEnum;
import com.analysis.enums.WebTypeEnum;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * Excel导出工具类
 * 用于导出References数据到Excel文件
 * 
 * @Date 2025/1/3
 * @Author 蒋棒
 */
public class ExcelExportUtils {
    
    private static final Logger logger = LoggerFactory.getLogger(ExcelExportUtils.class);
    
    // 日期时间格式化器
    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    
    // 列标题
    private static final String[] HEADERS = {
         "网站名称", "页面名称", "URL", "网站类型", "引用次数", "AI模型", "添加类型", "行业类型", "产品名称", "问题"
    };
    
    // 列宽度
    private static final int[] COLUMN_WIDTHS = {
        30, 35, 50, 25, 20, 25, 22, 25, 30, 40
    };
    
    /**
     * 导出References数据到Excel
     * 
     * @param referencesList References数据列表
     * @param sheetName 工作表名称
     * @return Excel文件的字节数组
     * @throws IOException IO异常
     */
    public static byte[] exportReferencesToExcel(List<References> referencesList, String sheetName) throws IOException {
        if (referencesList == null || referencesList.isEmpty()) {
            logger.warn("References数据列表为空，无法导出Excel");
            return new byte[0];
        }
        
        logger.info("开始导出References数据到Excel，数据量: {}", referencesList.size());
        
        try (Workbook workbook = new XSSFWorkbook()) {
            // 创建工作表
            Sheet sheet = workbook.createSheet(sheetName != null ? sheetName : "信源数据");
            
            // 创建标题行样式
            CellStyle headerStyle = createHeaderStyle(workbook);
            
            // 创建数据行样式
            CellStyle dataStyle = createDataStyle(workbook);
            
            // 创建日期样式
            CellStyle dateStyle = createDateStyle(workbook);
            
            // 设置列宽度
            setColumnWidths(sheet);
            
            // 创建标题行
            createHeaderRow(sheet, headerStyle);
            
            // 创建数据行
            createDataRows(sheet, referencesList, dataStyle, dateStyle);
            
            // 转换为字节数组
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            workbook.write(outputStream);
            byte[] excelBytes = outputStream.toByteArray();
            
            logger.info("References数据导出Excel完成，文件大小: {} bytes", excelBytes.length);
            return excelBytes;
            
        } catch (Exception e) {
            logger.error("导出References数据到Excel失败", e);
            throw new IOException("导出Excel失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 创建标题行样式
     */
    private static CellStyle createHeaderStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        
        // 设置背景色
        style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        
        // 设置边框
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        
        // 设置字体
        Font font = workbook.createFont();
        font.setBold(true);
        font.setFontHeightInPoints((short) 12);
        style.setFont(font);
        
        // 设置对齐方式
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        
        return style;
    }
    
    /**
     * 创建数据行样式
     */
    private static CellStyle createDataStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        
        // 设置边框
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        
        // 设置对齐方式
        style.setAlignment(HorizontalAlignment.LEFT);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        
        // 设置自动换行
        style.setWrapText(true);
        
        return style;
    }
    
    /**
     * 创建日期样式
     */
    private static CellStyle createDateStyle(Workbook workbook) {
        CellStyle style = createDataStyle(workbook);
        
        // 设置日期格式
        CreationHelper createHelper = workbook.getCreationHelper();
        style.setDataFormat(createHelper.createDataFormat().getFormat("yyyy-mm-dd hh:mm:ss"));
        
        return style;
    }
    
    /**
     * 设置列宽度
     */
    private static void setColumnWidths(Sheet sheet) {
        for (int i = 0; i < HEADERS.length; i++) {
            sheet.setColumnWidth(i, COLUMN_WIDTHS[i] * 256); // POI中列宽单位是1/256字符
        }
    }
    
    /**
     * 创建标题行
     */
    private static void createHeaderRow(Sheet sheet, CellStyle headerStyle) {
        Row headerRow = sheet.createRow(0);
        
        for (int i = 0; i < HEADERS.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(HEADERS[i]);
            cell.setCellStyle(headerStyle);
        }
    }
    
    /**
     * 创建数据行
     */
    private static void createDataRows(Sheet sheet, List<References> referencesList, 
                                     CellStyle dataStyle, CellStyle dateStyle) {
        int rowIndex = 1; // 从第二行开始（第一行是标题）

        // 填充数据
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        for (References references : referencesList) {
            Row row = sheet.createRow(rowIndex++);
            
            // ID
//            createCell(row, 0, references.getId(), dataStyle);
            
            // 用户ID
//            createCell(row, 1, references.getUserId(), dataStyle);
            
            // 网站名称
            createCell(row, 0, references.getWebName(), dataStyle);
            
            // 页面名称
            createCell(row, 1, references.getPageName(), dataStyle);
            
            // URL
            createCell(row, 2, references.getUrl(), dataStyle);
            
            // 网站类型
            createCell(row, 3, WebTypeEnum.getName(references.getWebType()), dataStyle);
            
            // 引用次数
            createCell(row, 4, references.getReferenceCount(), dataStyle);

            // AI模型
            createCell(row, 5, ModelChatClientEnum.getName(references.getAiModel()), dataStyle);
            
            // 添加类型
            createCell(row, 6, AddTypeEnum.getName(references.getAddType()), dataStyle);
            
            // 行业类型
            createCell(row, 7, references.getTradeType(), dataStyle);
            
            // 产品名称
            createCell(row, 8, references.getProductName(), dataStyle);
            
            // 问题
            createCell(row, 9, references.getQuestion(), dataStyle);
            
            // 页面创建时间
//            createCell(row, 10, references.getPageCreated(), dataStyle);
            
            // 启用状态
//            createCell(row, 13, references.getEnableStatus(), dataStyle);

            // 创建时间
//            if (references.getCreated() != null) {
//                createCell(row, 11, references.getCreated().format(dateFormatter), dateStyle);
//            } else {
//                createCell(row, 11, "", dataStyle);
//            }

        }
    }
    
    /**
     * 创建单元格
     */
    private static void createCell(Row row, int columnIndex, Object value, CellStyle style) {
        Cell cell = row.createCell(columnIndex);
        
        if (value == null) {
            cell.setCellValue("");
        } else if (value instanceof String) {
            cell.setCellValue((String) value);
        } else if (value instanceof Integer) {
            cell.setCellValue((Integer) value);
        } else if (value instanceof Long) {
            cell.setCellValue((Long) value);
        } else if (value instanceof Double) {
            cell.setCellValue((Double) value);
        } else if (value instanceof Boolean) {
            cell.setCellValue((Boolean) value);
        } else {
            cell.setCellValue(value.toString());
        }
        
        cell.setCellStyle(style);
    }
    
    /**
     * 生成文件名
     * 
     * @param prefix 文件名前缀
     * @return 生成的文件名
     */
    public static String generateFileName(String prefix) {
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
        return String.format("%s_%s.xlsx", prefix != null ? prefix : "信源数据", timestamp);
    }
}
